﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using XLETL.BLL;
using XLETL.Model;
using CodeProject.Dialog;
using XLETL.Common;

namespace XLETL.TaskManager.Forms
{
    public partial class LoginForm : Form
    {
        private bool IsAuthenticated = false;        
        private bool isExistRecord = true;
        private Admin admin = null;
        
        public bool IsClose = false;  // hold flag to announce the system's exit      

        public LoginForm()
        {
            InitializeComponent();

          try{
            admin = new Admin();
          }catch(Exception ex)
          {
            throw ex;
          }

            if (admin.CountAdminRecords() > 0)
            {
              lblRepPass.Visible = false;
              tbRepPassword.Visible = false;
              lblPassword.Location = new Point(lblPassword.Location.X, lblPassword.Location.Y + 10);
              tbPassword.Location = new Point(tbPassword.Location.X, tbPassword.Location.Y + 10);
            }
            else
            {
              isExistRecord = false;
              btnLogin.Text = "Create";
              lblInfo.Text = "Create Administrator login. Please enter Username, Password, Repeat Password and press Create button.";
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
          bool isPassMatch = true;
          bool isReAttemp = false;

          if (tbUsername.Text != "")
          {
            if (tbPassword.Text != "")
            {
              if (!isExistRecord && !tbPassword.Text.Equals(tbRepPassword.Text))
              {
                isPassMatch = false;
              }

              if (isPassMatch)
              {
                try
                {
                  // If status of login exist, then verify admin credentials
                  if (isExistRecord)
                  {
                    List<AdminInfo> adminList = admin.GetAdminRecords();

                    foreach (AdminInfo aInfo in adminList)
                    {
                      string decUsernameString = Cryptography.EnDeCrypt(aInfo.UserName, false);
                      string decPassString = Cryptography.EnDeCrypt(aInfo.Password, false);
                      if (decUsernameString.Equals(tbUsername.Text) && decPassString.Equals(tbPassword.Text))
                      {
                        IsAuthenticated = true;
                        break;
                      }
                    } 
                  }
                  else
                  {
                    AdminInfo adminInfo = new AdminInfo();
                    adminInfo.UserName = Cryptography.EnDeCrypt(tbUsername.Text.Trim(), true);
                    adminInfo.Password = Cryptography.EnDeCrypt(tbPassword.Text.Trim(), true);

                    IsAuthenticated = admin.SaveAdminCredentials(adminInfo);
                  }
                }
                catch (Exception ex)
                {
                  throw ex;
                }
              }
              else
              {
                isReAttemp = true;
                MsgBox.Show("Passwords do not match.", "Create Login Error", MessageBoxButtons.OK);
                tbRepPassword.Focus();
              }
            }
            else
            {
              isReAttemp = true;
              MsgBox.Show("Password field cannot be empty.", "Create Login Error", MessageBoxButtons.OK);
              tbPassword.Focus();
            }
          }
          else
          {
            isReAttemp = true;
            MsgBox.Show("Username field cannot be empty.", "Create Login Error", MessageBoxButtons.OK);
            tbUsername.Focus();
          }

          if (IsAuthenticated)
          {
            this.DialogResult = DialogResult.OK;
          }
          else if (!isReAttemp)
          {
            MsgBox.Show("Authentication failed.", "Login Error", MessageBoxButtons.OK);
            tbUsername.Focus();
          }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
          // If refuse to login then exit the application
          IsClose = true;
          this.DialogResult = DialogResult.Cancel;
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
          // In case of authentication fails make sure we correctly exit the application
          if (!IsAuthenticated)
          {
            IsClose = true;
          }
        }        
    }
}
